package cn.com.jinhao.provider.business.service.impl;

import cn.com.jinhao.hotline.commons.exception.BusinessErrorException;
import cn.com.jinhao.hotline.commons.vo.system.AddrResponseVO;
import cn.com.jinhao.provider.business.entity.Addr;
import cn.com.jinhao.provider.business.mapper.AddrMapper;
import cn.com.jinhao.provider.business.service.AddrService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class AddrServiceImpl implements AddrService {
    @Resource
    AddrMapper addrMapper;


    @Override
    public Map<String, Object> queryByPaid(String parentCode, int pageNo, int pageSize) {
        HashMap<String, Object> map = new HashMap<>(10);
        if (pageNo != 0 && pageSize != 0) {
            PageHelper.startPage(pageNo, pageSize);
            PageInfo<AddrResponseVO> pageInfo = new PageInfo<>(addrMapper.queryByPaid(parentCode));
            map.put("list", pageInfo);
            map.put("total", pageInfo.getTotal());
            map.put("pageSize", pageInfo.getPageSize());
            map.put("pageNo", pageInfo.getPageNum());
        } else {
            List<AddrResponseVO> addrResponseVOList = addrMapper.queryByPaid(parentCode);
            map.put("list", addrResponseVOList);
            map.put("total", addrResponseVOList.size());
        }
        return map;
    }

    @Override
    public Addr queryByCode(String code) {
        Example example = new Example(Addr.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code", code);
        return addrMapper.selectOneByExample(example);
    }

    @Override
    public String queryNameByCode(String code) throws Exception {
        Addr addr = Optional.ofNullable(this.queryByCode(code)).orElseThrow(() -> new BusinessErrorException("此地区编码不存在，请检查地区编码是否正确!"));
        return addr.getAddr();
    }
}
